const express = require('express')
const multiparty = require('multiparty')
const fs = require('fs')
const router = express.Router()

const Teacher = require('../../../models/Teacher')
const Course = require('../../../models/Course')
const User = require('../../../models/User')

const {
  downloadURI,
  uploadURI
} = require('../../../config/key')
const getCurTime = require('../../../utils/getCurTime')
const delArrOfOne = require('../../../utils/delArrOfOne')
const deleteFolder = require('../../../utils/deleteFolde')

// test api
router.get('/', (req, res) => {
  res.send('hello teacher')
})

/**
 * @description teacher upload course
 * @rotuer /api/teacher/uploadCourse
 * @method POST
 */
router.post('/uploadCourse', (req, res) => {
  const form = new multiparty.Form()
  const data = req.headers
  const description = decodeURIComponent(data.description)
  const coursename = decodeURIComponent(data.coursename)
  const type = decodeURIComponent(data.type)
  const courseType = decodeURIComponent(data.coursetype)
  const teacherName = decodeURIComponent(data.teachername)

  form.encoding = 'utf-8'
  form.uploadDir = uploadURI

  // 上传课程大小不能超过2G
  form.maxFilesSize = 2048 * 1024 * 1024
  form.parse(req, (err, fields, files) => {
    if (err) {
      throw err
    }

    User.findById(data.id)
      .then(user => {
        if (!user) {
          return res.send({
            status: 0,
            msg: '当前用户不存在...'
          })
        }

        const courseName = `${files.file[0].originalFilename}`
        if (!fs.existsSync(`${uploadURI}/movies/${data.id}`)) {
          fs.mkdirSync(`${uploadURI}/movies/${data.id}`)
        }

        if (fs.existsSync(`${uploadURI}/movies/${data.id}`) && !fs.existsSync(`${uploadURI}/movies/${data.id}/${coursename}`)) {
          fs.mkdirSync(`${uploadURI}/movies/${data.id}/${coursename}`)
        }
        // 重命名上传的文件
        fs.renameSync(files.file[0].path, `${uploadURI}/movies/${data.id}/${coursename}/${courseName}`)

        // 查询当前数据库中是否已经存在同名的课程
        Course.findOne({
            coursename
          })
          .then(course => {
            if (course) {
              return res.send({
                status: 0,
                msg: '当前课程名称已经存在，请使用其他课程名称',
                data: null
              })
            }

            // 将课程文件文件的路径存储在课程的数据库中
            const newCourse = new Course({
              coursename,
              description,
              price: `${data.price}￥`,
              teacherId: user._id,
              courseURI: `${downloadURI}movies/${data.id}/${coursename}`,
              type,
              courseType,
              teacherName
            })

            newCourse.save()
              .catch(err => {
                throw err
              })
            Teacher.findOne({
                teacherId: user._id.toString()
              })
              .then(teacher => {
                teacher.uploadCourse.push({
                  id: newCourse._id,
                  uploadTime: getCurTime()
                })
                teacher.save()
                  .then(user => {
                    return res.send({
                      status: 1,
                      msg: '上传成功',
                      data: {
                        courseName: newCourse.courseName,
                        description: newCourse.description
                      }
                    })
                  })
                  .catch(err => {
                    throw err
                  })
              })
              .catch(err => {
                throw err
              })
          })
      })
      .catch(err => {
        throw err
      })
  })
})


/**
 * @description teacher remove course
 * @router /api/teacher/delCourse
 * @method POST
 */
router.post('/delCourse', (req, res) => {
  const data = req.body
  Teacher.findOne({
      teacherId: data.teacherId
    })
    .then(teacher => {
      if (!teacher) {
        return res.send({
          status: 0,
          msg: '用户账号错误',
          data: null
        })
      }
      for (let i = 0; i < teacher.uploadCourse.length; i++) {
        if (data.courseId === (teacher.uploadCourse[i].id).toString()) {
          delArrOfOne(teacher.uploadCourse, i, 1)
          break
        }
      }
      teacher.save()
        .catch(err => {
          throw err
        })

      User.find()
        .then(userList => {
          // 判断当前用户是否购买该门课程
          for (let i = 0; i < userList.length; i++) {
            // 清除用户购买列表中的数据
            if (!userList[i].applyCourse.length) {
              continue
            }
            let applyCourseList = userList[i].applyCourse
            for (let j = 0; j < applyCourseList.length; j++) {
              if (data.courseId === applyCourseList[j].id.toString()) {
                delArrOfOne(applyCourseList, j, 1)
                userList[i].myCourseNum -= 1
                userList[i].save()
                  .catch(err => {
                    throw err
                  })
              }
            }
          }

          for (let i = 0; i < userList.length; i++) {
            // 清除用户购买列表中的数据
            if (!userList[i].collect.length) {
              continue
            }
            let collectCourseList = userList[i].collect
            for (let j = 0; j < collectCourseList.length; j++) {
              if (data.courseId === collectCourseList[j].id.toString()) {
                delArrOfOne(collectCourseList, j, 1)
                userList[i].save()
                  .catch(err => {
                    throw err
                  })
              }
            }

          }
        })
      Course.findByIdAndRemove(data.courseId, (err, ret) => {
          if (err) {
            res.send({
              status: 0,
              msg: '删除失败',
              data: null
            })
          }
          deleteFolder(`${uploadURI}/movies/${data.teacherId}/${ret.coursename}`)
          res.send({
            status: 1,
            msg: '删除成功',
            data: null
          })
        })
        .catch(err => {
          throw err
        })
    })
    .catch(err => {
      throw err
    })
})


/**
 * @description teacher update course
 * @router /api/teacher/updateCourse
 * @method POST
 */
router.post('/updateCourse', (req, res) => {
  const data = req.body
  Course.findByIdAndUpdate(data.id, {
    price: data.price,
    description: data.description,
    coursename: data.courseName,
    courseURI: `${downloadURI}movies/${data.teacherId}/${data.courseName}`
  }, (err, response) => {
    if (err) {
      return res.send({
        status: 0,
        msg: '修改失败',
        data: null
      })
    }
    let courseURI = response.courseURI
    let str = courseURI.substring(21, courseURI.length)
    fs.renameSync(`${uploadURI}${str}`, `${uploadURI}/movies/${data.teacherId}/${data.courseName}`)
    res.send({
      status: 1,
      msg: '修改成功',
      data: {
        ...response._doc
      }
    })
  })
})


/**
 * @description teacher find themSlef upload Course
 * @router /api/teacher/findAll
 * @method GET
 */
router.get('/findAll', (req, res) => {
  const teacherId = req.body.teacherId
  Teacher.findOne({
      teacherId
    }, (err, response) => {
      if (err) {
        throw err
      }
      Course.find({
          teacherId
        })
        .then(courseList => {
          res.send(courseList)
        })
        .catch(err => {
          throw err
        })
    })
    .catch(err => {
      throw err
    })
})


/**
 * @description 返回当前教师自己上传的课程
 * @router /api/teacher/teachCourse
 * @method get
 */
router.get('/teachCourse', (req, res) => {
  const data = req.query
  Course.find({
      teacherId: data.teacherId
    })
    .then(course => {
      res.send({
        status: 1,
        msg: '查询成功',
        data: [
          ...course
        ]
      })
    })

})


module.exports = router